package com.du;
/**
 * @author : DuJiabao
 * @Date : 2021/1/31 19:49
 * @Project : java-web
 * @File : ${FILE_NAME}
 * @Desc :
 */

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@WebServlet(name = "SendServlet", value = "/sendServlet")
public class SendServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("下载文件");
    // 文件名
    String filename = "地址.txt";
    ServletContext servletContext = getServletContext();
    // 获取文件类型
    String mimeType = servletContext.getMimeType("/file/" + filename);
    System.out.println("文件类型" + mimeType);
    response.setContentType(mimeType); // 设置文件类型
    // 设置请求头的内容,将文件名传过去编码格式为UTF-8
    // 告诉浏览器，这是需要下载的
    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("地址.txt", "UTF-8"));
    // 获取servlet的输入流
    InputStream resourceAsStream = servletContext.getResourceAsStream("/file/" + filename);
    // 获取响应的输出流
    ServletOutputStream outputStream = response.getOutputStream();
    // 将输入流的内容复制到输出流
    IOUtils.copy(resourceAsStream, outputStream);
  }
}
